#include "character.h"

Character::Character(int x, int z, Model &model)
  : model_(&model)
{
  x_ = x;
  z_ = z;
  orientation_ = NORTH;
}

void Character::Set(int x, int z, Direction orientation) {
  x_ = x;
  z_ = z;
  orientation_ = orientation;
}

Point Character::Move(Movement mov)
{
  int d, distance = 0;
  switch(mov) {
  case FRONT:
    distance = 1;
    break;
  case LEFT:
    d = (int) orientation_;
    d = (d - 1 + DIRS) % DIRS;
    orientation_ = (Direction)d;
    distance = 0;
    break;
  case RIGHT:
    d = (int) orientation_;
    d = (d + 1) % DIRS;
    orientation_ = (Direction)d;
    distance = 0;
    break;
  case BACK:
    distance = -1;
    break;
  default:
    break;
  }
  switch (orientation_) {
  case NORTH:
    x_ += distance;
    break;
  case EAST:
    z_ += distance;
    break;
  case SOUTH:
    x_ -= distance;
    break;
  case WEST:
    z_ -= distance;
    break;
  default:
    break;
  }
  return GetPosition();
}

void Character::Undo(Movement mov)
{
  Move((Movement) (MOVES - 1 - mov));
}

int Character::GetX()
{
  return x_;
}

int Character::GetZ()
{
  return z_;
}

Point Character::GetPosition()
{
  return Point(x_ + 0.5, kGroundHeight, z_ + 0.5);
}

Direction Character::GetOrientation()
{
  return orientation_;
}

void Character::Render(int rotation)
{
  if (model_ != NULL) {

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();

    // We know the position and the rotation, and that the model is always drawn with the base centered in (0, 0, 0)
    Point pos = GetPosition();
    glTranslatef(pos.x, pos.y, pos.z); // Put model in correct position
    glRotatef(-90 * (orientation_ + rotation), 0, 1, 0); // Rotate model according to character orientation

    model_->Render();

    glPopMatrix();
  }
}

void Character::PickRender(GLubyte color[])
{
  //TODO: Remove duplicated code
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  // We know the position and the rotation, and that the model is always drawn with the base centered in (0, 0, 0)
  Point pos = GetPosition();
  glTranslatef(pos.x, pos.y, pos.z); // Put model in correct position
  glRotatef(-90 * orientation_, 0, 1, 0); // Rotate model according to character orientation

  model_->PickRender(color);

  glPopMatrix();
}
